package org.kl.bf.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

/**
 * @Author hqm
 * @CreateTime 2014-3-22 上午3:12:37
 */
public class CRUDUtils {
	/**
	 * 创建分页请求.
	 */
	public static PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType, String orderType) {
		return new PageRequest(pageNumber - 1, pagzSize, buildSort(sortType, orderType));
	}

	/**
	 * 创建排序条件.
	 */
	public static Sort buildSort(String sortType, String orderType) {
		Sort sort = null;
		if (StringUtils.isNotBlank(sortType)) {
			String[] sortTypeArray = sortType.split(",");
			String[] orderTypeArray = orderType.split(",");
			Order[] orders = new Order[sortTypeArray.length];
			for (int i = 0; i < sortTypeArray.length; i++) {
				orders[i] = new Order(Direction.fromStringOrNull(orderTypeArray[i].trim()), sortTypeArray[i].trim());
			}
			sort = new Sort(orders);
		} else {
			sort = new Sort(Direction.DESC, "id");
		}
		return sort;
	}

	/**
	 * 创建排序条件.
	 */
	public static List<Order> buildOrder(String[] sortTypeArray, String[] orderTypeArray) {
		if (sortTypeArray != null) {
			if (orderTypeArray == null) {
				orderTypeArray = new String[0];
			}
			List<Order> orders = new ArrayList<Order>();
			for (int i = 0; i < sortTypeArray.length; i++) {
				if (orderTypeArray.length - 1 < i) {
					orders.add(new Order(Direction.ASC, sortTypeArray[i].trim()));
				} else {
					orders.add(new Order(Direction.fromStringOrNull(orderTypeArray[i].trim()), sortTypeArray[i].trim()));
				}
			}
			return orders;
		}
		return null;
	}

	public static String contractArray(Object[] origin, int x, int y) {
		if (origin != null && origin.length > x && origin.length > y && x <= y) {
			StringBuilder sb = new StringBuilder();
			for (int i = x; i <= y; i++) {
				sb.append((String) origin[i]+" ");
			}
			return sb.toString();
		}
		return "";
	}
}
